package cn.org.book.shop.web.controller.article;

import cn.org.book.shop.article.domain.ApArticle;
import cn.org.book.shop.article.domain.ApArticleConfig;
import cn.org.book.shop.article.domain.ApMaterial;
import cn.org.book.shop.article.service.IApArticleConfigService;
import cn.org.book.shop.article.service.IApArticleService;
import cn.org.book.shop.article.service.IApMaterialService;
import cn.org.book.shop.article.service.IApUserChannelService;
import cn.org.book.shop.common.annotation.Log;
import cn.org.book.shop.common.core.controller.BaseController;
import cn.org.book.shop.common.core.domain.AjaxResult;
import cn.org.book.shop.common.core.page.TableDataInfo;
import cn.org.book.shop.common.enums.BusinessType;
import cn.org.book.shop.common.utils.bean.CloudFileBean;
import cn.org.book.shop.common.utils.file.CloudFile;
import cn.org.book.shop.common.utils.file.QiNiuCloudFileUtils;
import cn.org.book.shop.common.utils.poi.ExcelUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 文章信息，存储已发布的文章Controller
 *
 * @author julywhj
 * @date 2020-11-17
 * @blame Android Team
 */
@RestController
@RequestMapping("/ap/article")
public class ApArticleController extends BaseController {
    @Resource
    private IApArticleService apArticleService;

    @Resource
    private IApMaterialService apMaterialService;
    @Resource
    private IApUserChannelService apUserChannelService;

    @Resource
    private IApArticleConfigService apArticleConfigService;

    private String filePath = System.getProperty("user.home");


    @PostMapping("/material")
    public AjaxResult material(@RequestBody List<ApMaterial> materials) {
        materials.forEach(this::saveMaterial);
        return AjaxResult.success();
    }

    private void saveMaterial(ApMaterial apMaterial) {
        if (apMaterial.getArticleId() != null) {
            ApArticle apArticle = apArticleService.selectApArticleById(apMaterial.getArticleId());
            if (apArticle != null) {
                List<ApMaterial> apMaterials = apMaterialService.selectApMaterialList(apMaterial);
                if (apMaterials.isEmpty()) {
                    apMaterial.setMaterialType(apArticle.getLayout());
                    apMaterial.setChannelId(apArticle.getChannelId());
                    apMaterial.setName(apArticle.getTitle().concat("-").concat(String.valueOf(apMaterial.getOrd())));
                    apMaterialService.insertApMaterial(apMaterial);
                }
            }
        }
    }

    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
        CloudFile cloudFile = new QiNiuCloudFileUtils();
        CloudFileBean cloudFileBean = new CloudFileBean(
                "2mXC2bkkH46J1P3XvnecyBPAX1y_K11Je5BYz2t4", "VUJ6_p-7VBMbSkYgI---WUzhzz3ZWMP1hHq1WAI-",
                "july-public-file", file.getOriginalFilename(), "http://pub.julywhj.cn"
        );
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        FileUtils.writeByteArrayToFile(new File(filePath.concat(File.separator)
                .concat("upload").concat(File.separator)
                .concat(f.format(new Date()))
                .concat(File.separator).concat(Objects.requireNonNull(file.getOriginalFilename()))), file.getBytes());
        CloudFileBean upload = cloudFile.upload(file.getBytes(), cloudFileBean);
        return AjaxResult.success(upload.getDownLoadUrl());
    }

    /**
     * 查询文章信息，存储已发布的文章列表
     */
    @PreAuthorize("@ss.hasPermi('ap:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(ApArticle apArticle) {
        startPage();
        List<ApArticle> list = apArticleService.selectApArticleList(apArticle);
        return getDataTable(list);
    }

    /**
     * 导出文章信息，存储已发布的文章列表
     */
    @PreAuthorize("@ss.hasPermi('ap:article:export')")
    @Log(title = "文章信息，存储已发布的文章", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ApArticle apArticle) {
        List<ApArticle> list = apArticleService.selectApArticleList(apArticle);
        ExcelUtil<ApArticle> util = new ExcelUtil<ApArticle>(ApArticle.class);
        return util.exportExcel(list, "article");
    }

    /**
     * 获取文章信息，存储已发布的文章详细信息
     */
    @PreAuthorize("@ss.hasPermi('ap:article:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(apArticleService.selectApArticleById(id));
    }

    /**
     * 新增文章信息，存储已发布的文章
     */
    @PreAuthorize("@ss.hasPermi('ap:article:add')")
    @Log(title = "文章信息，存储已发布的文章", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ApArticle apArticle) {
        apArticle.setIsDownLoad(0);
        changeChannel(apArticle);
        apArticleService.insertApArticle(apArticle);
        saveApArticleConfig(apArticle);
        return AjaxResult.success(apArticle);
    }

    /**
     * 修改文章信息，存储已发布的文章
     */
    @PreAuthorize("@ss.hasPermi('ap:article:edit')")
    @Log(title = "文章信息，存储已发布的文章", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ApArticle apArticle) {
        changeChannel(apArticle);
        return apArticleService.updateApArticle(apArticle) > 0 ? AjaxResult.success(apArticle) : AjaxResult.error();
    }

    private void changeChannel(ApArticle apArticle) {
        apArticle.setChannelName(apUserChannelService.selectApUserChannelById(apArticle.getChannelId()).getName());
    }

    private void saveApArticleConfig(ApArticle apArticle) {
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(apArticle.getId());
        apArticleConfigService.insertApArticleConfig(config);
    }

    /**
     * 删除文章信息，存储已发布的文章
     */
    @PreAuthorize("@ss.hasPermi('ap:article:remove')")
    @Log(title = "文章信息，存储已发布的文章", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(apArticleService.deleteApArticleByIds(ids));
    }
}
